package com.dpiinc.TechPage.api

import com.dpiinc.TechPage.AWLog
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

fun <T> Observable<T>.asyncSubscribe(response: (T) -> Unit) {
    this.asyncSubscribe(response, {})
}

fun <T> Observable<T>.asyncSubscribe(response: (T) -> Unit, throwable: (Throwable) -> Unit) {
    this.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                AWLog.i("asyncSubscribe subscribe$it.toString()")
                response(it)
            }, {
                AWLog.e("asyncSubscribe throwable$it.toString()")
                throwable(it)
            })
            .addToBag()
}

fun <T> Maybe<T>.asyncSubscribe(response: (T) -> Unit) {
    this.asyncSubscribe(response, {})
}

fun <T> Maybe<T>.asyncSubscribe(response: (T) -> Unit, throwable: (Throwable) -> Unit) {
    this.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                AWLog.i(it.toString())
                response(it)
            }, {
                AWLog.e(it.toString())
                throwable(it)
            })
            .addToBag()
}

@Suppress("unused")
fun Disposable.addToBag() {
    DisposablePoolHelper.add(this)
}
